import axios from 'axios'

const authApi = axios.create({
  baseURL: '/idserver/core',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json',
    'Access-Control-Allow-Origin': '*'
  },
  timeout: 10000
})

// 获取token
export const getToken = () => {
  const params = new URLSearchParams()
  params.append('scope', 'fbox')
  params.append('client_id', '68db2e8bda8d47b5b5db7eaf71c7dcdd')
  params.append('client_secret', '76dc724c95004acab25482d344dab407')
  params.append('grant_type', 'client_credentials')
  
  return new Promise((resolve, reject) => {
    authApi.post('/connect/token', params)
      .then(response => {
        if (response.data && response.data.access_token) {
          resolve(response)
        } else {
          reject(new Error('Token not found in response'))
        }
      })
      .catch(error => {
        console.error('Token request error:', error.response || error)
        reject(error)
      })
  })
}

// 创建带token的请求实例
export const createAuthApi = (token) => {
  return axios.create({
    baseURL: 'https://fbox360.com/api',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    timeout: 10000
  })
}

// 添加响应拦截器
authApi.interceptors.response.use(
  response => response,
  error => {
    console.error('Request error:', {
      status: error.response?.status,
      data: error.response?.data,
      config: error.config
    })
    return Promise.reject(error)
  }
) 